package sdfi.lee.Filter;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sdfi.lee.Logger.MyLogger;

/**
 * Servlet Filter implementation class ParamFilter
 */
public class ParamFilter implements Filter {

    /**
     * Default constructor. 
     */
    public ParamFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		
		// pass the request along the filter chain
		HttpServletRequest httprequest=(HttpServletRequest)request;
		try
		{
			String realpath=httprequest.getContextPath();
			String uri=httprequest.getRequestURL().toString();
		
			String url=realpath+"/testreal/"+uri.substring(uri.lastIndexOf("/")+1,uri.indexOf("?"));
			String params=uri.substring(uri.indexOf("?")+1);
			
			StringTokenizer st=new StringTokenizer(params,"#");
			while(st.hasMoreElements())
			{
				String obje=st.nextElement().toString();
				int index=obje.indexOf("|");
				if(index!=-1)
					{
						url+=obje.substring(0,index)+"="+obje.substring(index+1)+"&";
					}
				else
				((HttpServletResponse)response).sendError(404, "对不起路径不合法");
				
			}
			url=url.substring(0,url.lastIndexOf("&"));
		
			httprequest.getRequestDispatcher(url);
		}
		catch(Exception ee)
		{
			System.out.println("Exception");
			ee.printStackTrace();
			((HttpServletResponse)response).sendError(404, "对不起路径不合法");
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
